package tree;

import java.util.*;

public class BinaryTreeRightSideView199 {
    public List<Integer> rightSideView(TreeNode root) {
        if (root == null) {
            return Collections.emptyList();
        }
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);

        List<Integer> result = new ArrayList<>();
        while (!q.isEmpty()) {
            int count = q.size();
            for (int i = 0; i < count; i++) {
                TreeNode n = q.poll();
                if (n.left != null) {
                    q.offer(n.left);
                }
                if (n.right != null) {
                    q.offer(n.right);
                }
                if (i == count-1) {
                    result.add(n.val);
                }
            }
        }
        return result;
    }
}
